import asyncio
import os
import sys
import time
project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_path)
from common.pkg.task_util import TaskProcess


class DemoProcess(TaskProcess):

    async def run(self, worker_id):
        while not self.stopped:
            print(time.time())
            await asyncio.sleep(1)


async def core(cls, args):
    tasks = []
    for i in range(args.worker):
        tasks.append(cls().run(i))
    results = await asyncio.gather(*tasks)
    await cls.release_process()


if __name__ == '__main__':
    from argparse import ArgumentParser
    from importlib import import_module
    import asyncio

    parser = ArgumentParser()
    parser.add_argument("--worker", dest="worker", type=int, default=1, help="消费者数量")
    parser.add_argument("--env", dest="env", type=str, default="prod", help="当前环境， local dev test uat prod")
    parser.add_argument("--include", dest="include", default="", help="额外需要包含的导包路径")
    parser.add_argument("--process_path", dest="process_path", help="消费者类所在路径，用.区分层级关系")
    args = parser.parse_args()

    try:
        i = args.process_path.rfind(".")
        assert i >= 0, "无法找到消费者类,eg:module.cls"
        module_name = args.process_path[:i]
        cls_name = args.process_path[i+1:]
        module = import_module(f"{module_name}")
        cls = getattr(module, cls_name, None)

        loop = asyncio.get_event_loop()

        loop.run_until_complete(cls.init_process(loop, args))
        loop.run_until_complete(core(cls, args))

        loop.close()
    except Exception as e:
        print(f"异常: {e}")
